﻿using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using System;

namespace Syspetro.ServiceCore
{
    public static class LogExtensions
    {
        /// <summary>
        /// 添加默认日志拓展
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="configAction"></param>
        /// <returns></returns>
        public static IHostBuilder UseSerilogDefault(this IHostBuilder builder, Action<LoggerConfiguration> configAction = default)
        {
            builder.UseSerilog((hostingContext, services, loggerConfiguration) =>
            {
                // 定义日志输出
                if (configAction != null)
                {
                    var config = loggerConfiguration
                        .ReadFrom.Configuration(hostingContext.Configuration)//配置文件中读取配置
                        .Enrich.FromLogContext();
                    configAction.Invoke(config);
                }
                else
                {
                    // 加载配置文件
                    var configFile = loggerConfiguration
                        .ReadFrom.Configuration(hostingContext.Configuration)//配置文件中读取配置
                        .Enrich.FromLogContext();

                    configFile
                        .MinimumLevel.Debug()
                        .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Debug);

                    //只记录某个级别的日志
                    configFile.MinimumLevel.Error()
                        .WriteTo.Logger(fileLogger => fileLogger
                        .Filter.ByIncludingOnly(p => p.Level.Equals(LogEventLevel.Error))
                        .WriteTo.File(path: "./logs/Error/.txt", rollingInterval: RollingInterval.Day));

                    //只记录某个级别的日志
                    configFile.MinimumLevel.Warning()
                        .WriteTo.Logger(fileLogger => fileLogger
                        .Filter.ByIncludingOnly(p => p.Level.Equals(LogEventLevel.Warning))
                        .WriteTo.File(path: "./logs/Warning/.txt", rollingInterval: RollingInterval.Day));

                    //只记录某个级别的日志
                    configFile.MinimumLevel.Information()
                        .WriteTo.Logger(fileLogger => fileLogger
                        .Filter.ByIncludingOnly(p => p.Level.Equals(LogEventLevel.Information))
                        .WriteTo.File(path: "./logs/Infor/.txt", rollingInterval: RollingInterval.Day));
                }
            });
            return builder;
        }
    }
}
